- Changing the original value does NOT update the copy:
let age = 100;
let age2 = age;
console.log(age, age2); // 100, 100
age = 200;
console.log(age, age2); // 200, 100
-
Unlike strings, updating values in arrays changes the original and the
copy referenced:
const players = ["Wes", "Sarah", "Ryan", "Poppy"];
const team = players;
console.log(players, team);
team[3] = "Lux";
console.log(team); // 'Wes', 'Sara', 'Ryan', 'Lux'
console.log(players); // 'Wes', 'Sara', 'Ryan', 'Lux'
Make a copy instead of a reference using:
Array.slice()
const team2 = players.slice();
Array.concat()
const team3 = [].concat(players);
Spread operator [... array]
const team5 = [...players];
Array.from()
const team6 = Array.from(players);
Above methods will make copy of an array without changing the original.
- The same thing applies when referencing objects :
const person = {
name: "Wes Bos",
age: 80,
};
Updating a reference also changes the original:
const captain = person; // this makes a reference to person, not a copy
captain.number = 99;
console.log(person); // {name: "Wes Bos", age: 80, number: 99};
const cap2 = Object.assign({}, person, { number: 99 });
Or make a shallow copy using ...spread operator
const cap3 = { ...person };